package util

import (
	"bytes"
	"fmt"
	"github.com/astaxie/beego/logs"
	"os/exec"
	"strings"
	"time"
)

func RunCommand(name string, args []string) (string, error) {
	var buildLog []string
	strings.Join(args, " ")
	cmd := exec.Command(name, args...)
	fmt.Printf("args=%v", args)
	buildLog = append(buildLog, fmt.Sprintf("docker %s", strings.Join(args, " ")))
	// 命令的错误输出和标准输出都连接到同一个管道
	stdout, err := cmd.StdoutPipe()
	cmd.Stderr = cmd.Stdout

	if err = cmd.Start(); err != nil {
		return "", err
	}
	// 从管道中实时获取输出并打印到终端
	for {
		tmp := make([]byte, 128)
		_, err := stdout.Read(tmp)
		//fmt.Print(string(tmp))
		buildLog = append(buildLog, string(tmp))
		if err != nil {
			break
		}
	}
	str := bytes.Buffer{}
	for _, log := range buildLog {
		str.WriteString(log + "\n")
	}
	log := str.String()
	fmt.Printf("build log ：%v\n", buildLog)
	if err = cmd.Wait(); err != nil {
		//docker build命令有问题，直接退出了
		fmt.Printf("cmd wait err=%v\n", err)
		return log, err
	}

	return log, nil
}
func ExecCommond(name string, args []string) (string, string, error) {
	cmd := exec.Command(name, args...)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout // 标准输出
	cmd.Stderr = &stderr // 标准错误
	err := cmd.Run()
	outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
	fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)
	if err != nil {
		logs.Error("cmd.Run() failed with %s\n", err)
		return outStr, errStr, err
	}
	return outStr, errStr, nil
}
func tobuildTime() {
	fmt.Println("开始%v", time.Now())
	time.Sleep(time.Second * 5)
	fmt.Println("结束", time.Now())
}
